import { useEffect, useState } from 'react';
import { Layout, App } from 'antd';
import { useRequest } from 'ahooks';
import Header from './components/header';
import HistoryChat from './components/history-chat2';
import Homepage from './components/homepage2';
import HomepageMobile from './components/homepage';
import Chat from './components/chat';
import { Header as LayoutHeader } from 'antd/es/layout/layout';
import './styles/app-qa.css';

import Back from '@/components/router/Back';
import { useInitializeData, useWorkBench } from '@/store/configStore';
import { useRouter } from '@/router/hooks';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import orchestrationService from '@/api/services/orchestrationService';
import { useUserInfo, useUserState } from '@/store/userStore';
import useWindowWidth from '@/hooks/event/use-window-width';
import Dashboard from '@/pages/report';
import Report2 from '@/pages/report/indexv2';
import metahumanService from '@/api/services/metahumanService';
import { useMetahumanStore } from '@/store/metahumanStore';

import { StartChatFnProps } from '../chat/tools/constants';
import { StreamResponseType } from '../chat/tools/fetch';
import { AppType, AppWorkbenchType } from '@/common/app/constants';
import { useChatActions } from '@/store/chatStore';

interface AppQAProps {
  onStartChat?: (e: StartChatFnProps) => Promise<
    StreamResponseType & {
      isNewChat?: boolean;
    }
  >;
  workflowDebug?: boolean;
}

const AppQA = ({ onStartChat, workflowDebug = false }: AppQAProps) => {
  const {
    special_app_lable,
    setAppDetail,
    setInputGuides,
    configurations,
    setFusionAppId,
    setSubAppDetail,
    isInOrchestrationPage,
    showAgentHistory,
    setShowAgentHistory,
    setIsLoadingAgentHistroy,
    isLoadingAgentHistroy,
    fusionAppId,
    appDetail
  } = useOrchestrationStore();

  // 数字人 store
  const {
    virtualAvatarName,
    virtualAvatarVoice,
    stop: storeStop,
    setIsMuted,
    reset,
    setIsMetahumanStart,
    setAppId,
    setPermissionConfig, setIsPermissionConfigLoading, setVirtualAvatarEnabled, setVirtualAvatarId, setVirtualSpeakerId, setVirtualAvatarUrl, setVirtualAvatarName, setVirtualAvatarVoice } = useMetahumanStore();

  const [currentView, setCurrentView] = useState<'homepage' | 'history' | 'chat' | 'dashboard'>(
    'homepage',
  );

  const [lastView, setLastView] = useState<'homepage' | 'history' | 'chat' | 'dashboard'>(
    'homepage',
  );
  const isSpecialApp = special_app_lable === '招生助手';

  const router = useRouter();

  const [chatMessage, setChatMessage] = useState<string>('');
  const [chatId, setChatId] = useState<string>('');
  const { isPc } = useWindowWidth();
  const { setIsDeepMode } = useChatActions();

  const { message } = App.useApp();

  const searchParams = new URLSearchParams(location.search);
  const appId = searchParams.get('appId') || '';

  const isInChatPage = location.pathname.includes('/apps/chat') || location.pathname.includes('/apps/fusion');

  const isConfigAvailable = configurations.length != 0;
  const initializeData = useInitializeData();

  // 使用 useRequest 获取数字人权限配置
  const { run: fetchMetahumanPermissionConfig } = useRequest(
    async (appId: string) => {
      setIsPermissionConfigLoading(true);
      try {
        const config = await metahumanService.getMetahumanPermissionConfig(appId, isInChatPage ? AppWorkbenchType.public : AppWorkbenchType.manage);
        setPermissionConfig(config);
        setVirtualAvatarEnabled(config.metahumanEnabled);
        setAppId(appId);
        setVirtualAvatarId(config.avatarId);
        setVirtualSpeakerId(config.speakerId);
        setVirtualAvatarUrl(config.previewAvatarUrl);
        setVirtualAvatarName(config.avatarName || config.avatarId);
        setVirtualAvatarVoice(config.speakerName || config.speakerId);
        return config;
      } catch (error) {
        setPermissionConfig(null);
      } finally {
        setIsPermissionConfigLoading(false);
      }
    },
    {
      manual: true, // 手动触发，不自动执行
    }
  );

  const metahumanStop = async () => {
    await storeStop();
  }

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const chatId = params.get('chatId') || '';
    if (chatId && currentView !== 'chat' && !isInOrchestrationPage) {
      setChatId(chatId);
      setCurrentView('chat');
      setLastView('homepage');
    }

    // setIsMuted(false);
    metahumanStop()
    setIsMetahumanStart(false);
    window.addEventListener('beforeunload', metahumanStop);
    return () => {
      window.removeEventListener('beforeunload', metahumanStop);
      metahumanStop()
      !isInOrchestrationPage && reset();
    }
  }, [])

  const handleViewChange = (
    view: 'homepage' | 'history' | 'chat' | 'dashboard',
    message?: string,
  ) => {
    console.log('view', view, message, currentView);
    const params = new URLSearchParams(window.location.search);

    if (view == 'chat' && currentView == 'history' && params.get('chatId')) {
      setChatId(params.get('chatId') || '');
      setLastView(currentView);
      setCurrentView(view);
      handleChatItemClick(params.get('chatId') || '');
    } else {
      setLastView(currentView);
      setCurrentView(view);
      if (message) {
        setChatMessage(message);
        setChatId(''); // 清空chatId，因为是从新消息开始聊天
      }
    }
  };

  const fetchInputGuides = async () => {
    if (!appId) return;
    try {
      const res = await orchestrationService.getAppInputGuide(appId);
      if (res.input_guide) {
        const guides = res.input_guide.map((guide: string, index: number) => ({
          id: String(index + 1),
          content: guide,
        }));
        setInputGuides(guides);
      }
    } catch (error) {
      message.error('获取输入引导失败');
    }
  };

  useEffect(() => {
    const fetchAppDetail = async () => {
      if (!appId) {
        // message.error('未获取到应用ID');
        return;
      }

      try {
        // const isInChatPage = location.pathname.includes('/apps/chat');
        const appDetail = await orchestrationService.getAppDetailV2(
          appId,
          isInChatPage ? AppWorkbenchType.public : AppWorkbenchType.manage,
        );
        // 设置应用详情到store

        setAppDetail(appDetail);
      } catch (error) {
        console.error('获取应用详情失败', error);
      } finally {
      }
    };

    !isConfigAvailable && fetchAppDetail();
    fetchInputGuides();

    // 初始化获取数字人权限配置
    if (appId && !isInOrchestrationPage && initializeData?.enableMetahuman) {
      fetchMetahumanPermissionConfig(appId);
    }

    // 默认启动深度思考
    setIsDeepMode(true);
    return () => {
      const isOrchestrationPath = location.pathname.includes('/apps/orchestration');
      !isOrchestrationPath && setAppDetail({});
    };
  }, [appId, initializeData?.enableMetahuman]);

  // useEffect(() => {
  //   if (appDetail?.appType === AppType.fusion) {
  //     storeStop();
  //     if (fusionAppId) {
  //       fetchMetahumanPermissionConfig(fusionAppId);
  //     } else {
  //       reset();
  //     }
  //   }
  // }, [fusionAppId]);

  const handleChatItemClick = (selectedChatId: string) => {
    console.log('点击历史对话');
    setChatId(selectedChatId);
    setChatMessage(''); // 清空message，因为是加载已有对话
    setCurrentView('chat');
    if (!isPc) {
      setShowAgentHistory(false);
    }
  };
  //触发更新
  const onUpdateHistory = () => {
    setIsLoadingAgentHistroy(!isLoadingAgentHistroy);
  };

  const { username } = useUserInfo();
  const { isGuest } = useUserState();

  return (
    <div
      className={`app-qa-container ${showAgentHistory
        ? 'bg-WhiteSmoke'
        : !isPc
          ? 'flex h-full w-full'
          : !isInOrchestrationPage
            ? 'bg-white'
            : 'rounded-[12px] bg-white'
        }`}
    >
      <Layout
        className={`h-full ${!isInOrchestrationPage ? '' : 'rounded-[12px]'}`}
        style={{
          // height: '100vh',
          overflow: 'hidden',
        }}
      >
        {/* {currentView === 'chat'  &&  */}
        {(!showAgentHistory || isPc) && (
          <Header
            currentView={currentView}
            onHistoryClick={() => {
              if (!isPc) {
                handleViewChange('history');
              }
              setShowAgentHistory(!showAgentHistory);
            }}
            onHomeClick={() => {
              setFusionAppId('');
              setSubAppDetail(null);
              handleViewChange('homepage');
              setShowAgentHistory(false);
              const params = new URLSearchParams(window.location.search);
              params.set('chatId', '');
              const newUrl = `${window.location.pathname}?${params.toString()}`;
              router.push(newUrl);
            }}
            onDashboardClick={() => handleViewChange('dashboard')}
            workflowDebug={workflowDebug}
            showAgentHistory={showAgentHistory}
          />
        )}
        {/* } */}
        <Layout.Content className={`app-qa-content h-full`} style={{ flex: 1, overflow: 'auto' }}>
          {currentView !== 'dashboard' && (
            <div className="flex size-full flex-grow items-center overflow-auto [-ms-overflow-style:none] [scrollbar-width:none]">
              {/* {currentView === 'homepage' && !showAgentHistory && ( */}
              {currentView === 'homepage' && (
                <Homepage
                  onChatStart={(msg) => handleViewChange('chat', msg)}
                  workflowDebug={workflowDebug}
                  widthFlag={true}
                />
              )}
              {/* {currentView === 'chat' && !showAgentHistory && ( */}
              {currentView === 'chat' && (
                <Chat
                  workflowDebug={workflowDebug}
                  initialMessage={chatMessage}
                  chatId={chatId}
                  onStartChat={onStartChat}
                  onUpdateHistory={onUpdateHistory}
                />
              )}
              {showAgentHistory && (
                // {currentView === 'history' && (
                <HistoryChat
                  handleViewChange={handleViewChange}
                  onChatItemClick={handleChatItemClick}
                  onClose={() => handleViewChange(lastView)}
                />
              )}
            </div>
          )}

          {currentView === 'dashboard' && !showAgentHistory && isSpecialApp && <Report2 />}

          {currentView === 'dashboard' && !showAgentHistory && !isSpecialApp && <Dashboard />}
        </Layout.Content>
      </Layout>
    </div>
  );
};

export default AppQA;
